package org.qtk.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

public class Request {

	private String method;
	private String url;
	private Map<String, List<String>> parameterMapValues;
	private InputStream is;
	private String requestInfo;

	public String getUrl() {
		return url;
	}

	public String getMethod() {
		return method;
	}

	public Request() {
		method = "";
		url = "";
		parameterMapValues = new HashMap<>();
		requestInfo = "";
	}

	public Request(InputStream is) {
		this();
		this.is = is;
		byte[] data = new byte[20480];
		int len;
		try {
			len = is.read(data);
			requestInfo = new String(data, 0, len);
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		System.out
				.println("================================================== request ==================================================\r\n"
						+ requestInfo + "\r\n\r\n");
		parseRequestInfo();
	}

	/**
	 * 解析头信息
	 */
	private void parseRequestInfo() {
		if (requestInfo == null
				|| (requestInfo = requestInfo.trim()).equals("")) {
			return;
		}
		String paramStr = "";

		// 1.获取请求方式
		String firstLine = requestInfo
				.substring(0, requestInfo.indexOf("\r\n"));
		int idx = requestInfo.indexOf("/");
		this.method = firstLine.substring(0, idx).trim();

		// 2.获取url
		String url = firstLine.substring(idx, firstLine.indexOf("HTTP/"))
				.trim();
		if (this.method.equalsIgnoreCase("POST")) {
			this.url = url;
			paramStr = requestInfo.substring(requestInfo.lastIndexOf("\r\n"))
					.trim();
		} else {
			if (url.contains("?")) {
				String[] urlArray = url.split("\\?");
				this.url = urlArray[0];
				paramStr = urlArray[1];
			} else {
				this.url = url;
			}
		}

		if (paramStr != null || !(paramStr = paramStr.trim()).equals("")) {
			parseParamKeyValues(paramStr);
		}
	}

	// 3.将请求参数封装到map
	private void parseParamKeyValues(String paramStr) {
		StringTokenizer token = new StringTokenizer(paramStr, "&");
		while (token.hasMoreTokens()) {
			String keyValue = token.nextToken();
			String[] keyValues = keyValue.split("=");
			if (keyValues.length == 1) {
				keyValues = Arrays.copyOf(keyValues, 2);
				keyValues[1] = null;
			}
			String key = keyValues[0].trim();
			String value = null == keyValues[1] ? null : decode(
					keyValues[1].trim(), "utf8");
			// 转换成map
			if (!parameterMapValues.containsKey(key)) {
				parameterMapValues.put(key, new ArrayList<String>());
			}
			List<String> values = parameterMapValues.get(key);
			values.add(value);
		}
	}

	/**
	 * 根据页面的name获取对应的值
	 * 
	 * @param name
	 * @return
	 */
	public String getParameter(String name) {
		String[] values = getParameters(name);
		if (null == values) {
			return null;
		} else {
			return values[0];
		}
	}

	/**
	 * 根据页面的name获取对应的多个值
	 * 
	 * @param name
	 * @return
	 */
	public String[] getParameters(String name) {
		List<String> values = null;
		if ((values = parameterMapValues.get(name)) == null) {
			return null;
		} else {
			return values.toArray(new String[0]);
		}
	}

	private String decode(String value, String code) {
		try {
			return URLDecoder.decode(value, code);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

}
